# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  
@software: PyCharm 
@file: class_lazyproperty.py 
@time: 2019/6/13 15:34
"""

'''
使用延迟计算属性：目的为了提升性能
'''

# class LazyProperty:
#     def __init__(self, func):
#         self.func = func
#
#     def __get__(self, instance, owner):
#         if instance is None:
#             return self
#         else:
#             value = self.func(instance)
#             setattr(instance, self.func.__name__, value)
#             return value



# 为避免圆的面积和周长可修改，增加如下函数就可以限制
def lazyproperty(func):
    name = '_lazy_' + func.__name__
    @property
    def lazy(self):
        if hasattr(self, name):
            return getattr(self, name)
        else:
            value = func(self)
            setattr(self, name, value)
            return value
    return lazy


import math

class Circle:
    def __init__(self, radius):
        self.radius = radius

    # @LazyProperty
    @lazyproperty
    def area(self):
        print('Computing area')
        return math.pi * self.radius ** 2

    # @LazyProperty
    @lazyproperty
    def perimeter(self):
        print('Computing perimeter')
        return 2 * math.pi * self.radius

c = Circle(4.0)
print(c.radius)
print(c.area)
# 使用lazyproperty(func)方法后那c.area/c.perimetery不能被修改了
# c.area=26
# print(c.area)

print(c.perimeter)

print(c.area)
print(c.perimeter)
print('把圆半径删除，它的面积和周长不会改变')
del(c.radius)
print(vars(c))
print(vars(c))